from flask import Flask, render_template, url_for, session, redirect, flash
from flask_bootstrap import Bootstrap5
from flask_moment import Moment
from flask_wtf import FlaskForm
from wtforms import StringField,SubmitField
from wtforms.validators import DataRequired
from datetime import datetime
import os
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_mail import Mail, Message
from threading import Thread

app = Flask(__name__)
basedir = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:123456@localhost/bigblog'
# app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://postgres:123456@localhost/bigblog'
# app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'data.sqlite')
app.config['SQLALCHEMY_TRACK_MODIFICATION'] = False

# 邮箱配置
app.config['MAIL_SERVER'] = 'smtp.qq.com'
app.config['MAIL_POST'] = 465
app.config['MAIL_USE_SSL'] = True
app.config['MAIL_USERNAME'] = '你自己的邮箱'
app.config['MAIL_PASSWORD'] = '你自己的邮箱授权码'
app.config['Flasky博客邮件主题前缀'] = '[Flasky博客]'
app.config['Flasky邮件发送者'] = 'Flasky管理员<你自己的邮箱>'
app.config['FLASKY管理员'] = '你自己的邮箱'

db = SQLAlchemy(app)
migrate = Migrate(app, db)
bootstrap = Bootstrap5(app)
moment = Moment(app)
mail = Mail(app)
app.config['SECRET_KEY'] = 'abcdefgwjkdfsawerew'

def send_async_email(app, msg):
    with app.app_context():
        mail.send(msg)

def send_email(to, subject, template, **kwargs):
    msg = Message(app.config['Flasky博客邮件主题前缀']+subject, sender=app.config['Flasky邮件发送者'], recipients=[to])
    msg.body = render_template(template+'.txt', **kwargs)
    msg.html = render_template(template+'.html', **kwargs)
    thr = Thread(target=send_async_email, args=[app, msg])
    thr.start()
    return thr

class Role(db.Model):
    __tablename__ = 'roles'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), unique=True)

    users = db.relationship('User', backref='role', lazy='dynamic')

    def __repr__(self):
        return f'<Role {self.name}>'

class User(db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), unique=True, index=True)

    role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))

    def __repr__(self):
        return f'<User {self.username}>'



class NameForm(FlaskForm):
    name = StringField('你叫什么名字？', validators=[DataRequired()])
    submit = SubmitField('确定')

@app.route('/', methods=['GET', 'POST'])
@app.route('/index', methods=['GET', 'POST'])
def index():
    form = NameForm()
    if form.validate_on_submit():
        # old_name = session.get('name')
        # if old_name is not None and old_name != form.name.data:
        #     flash('你改变了输入的名字！', 'danger')
        # session['name'] = form.name.data
        user = User.query.filter_by(username=form.name.data).first()
        if user is None:
            user = User(username=form.name.data)
            db.session.add(user)
            db.session.commit()
            session['known'] = False
        else:
            session['known'] = True
        session['name'] = form.name.data
        if app.config['FLASKY管理员']:
            send_email(app.config['FLASKY管理员'], '新朋友加入', 'mail/new_user', user=user)
        form.name.data = ''
        return redirect(url_for('index'))
    return render_template('index.html', form = form, name=session.get('name'), known=session.get('known', False), current_time=datetime.utcnow())

@app.route('/name/')
@app.route('/name/<name>')
def user(name=None):
    return render_template('user.html', name=name)

@app.shell_context_processor
def make_shell_context():
    return dict(db=db, User=User, Role=Role)